const http = require('http');
const https = require('https');
const fs = require('fs');
const url = require('url');

const KNOWLEDGE_BASE_ID = '1872578144305889280';
const TOKEN = 'fb1a97a6c40035f74612f1f2b11f5eaa.saDHLrKCG6WxYtCA';

const server = http.createServer((req, res) => {
 const parsedUrl = url.parse(req.url, true);
 const path = parsedUrl.pathname;
 const method = req.method;

 if (path === '/send' && method === 'POST') {
   let body = '';
   req.on('data', chunk => {
     body += chunk.toString();
   });
   req.on('end', () => {
     try {
       const { message } = JSON.parse(body);
       if (!message) {
         return res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Message is required' }));
       }
       res.writeHead(200, { 'Content-Type': 'text/event-stream' });
       const requestData = parseInput(message);
       const options = {
         hostname: 'open.bigmodel.cn',
         path: '/api/paas/v4/chat/completions',
         method: 'POST',
         headers: {
           'Content-Type': 'application/json',
           'Authorization': `Bearer ${TOKEN}`
         }
       };

       const apiReq = https.request(options, apiRes => {
         apiRes.on('data', chunk => {
           try {
             const data = JSON.parse(chunk.toString().replace('data:', '').trim());
             if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
               res.write(data.choices[0].delta.content);
             }
           } catch (error) {
             // Do nothing
           }
         });
         apiRes.on('end', () => {
           res.end();
         });
       });

       apiReq.on('error', error => {
         console.error('API Request Error:', error);
         res.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'API Request Failed' }));
       });

       apiReq.write(requestData);
       apiReq.end();
     } catch (error) {
       res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Invalid JSON' }));
     }
   });
 } else if (path === '/') {
   fs.readFile('index.html', (err, data) => {
     if (err) {
       res.writeHead(404, { 'Content-Type': 'text/html' }).end('404 Not Found');
     } else {
       res.writeHead(200, { 'Content-Type': 'text/html' }).end(data);
     }
   });
 } else {
   res.writeHead(404, { 'Content-Type': 'text/html' }).end('404 Not Found');
 }
});

server.listen(5500, () => {
 console.log('Server is running on port 5500');
});

function parseInput(message) {
 return JSON.stringify({
   model: "glm-4-long",
   stream: true,
   temperature: 0.5,
   top_p: 0.5,
   tools: [{ type: "retrieval", retrieval: { knowledge_id: KNOWLEDGE_BASE_ID } }],
   messages: [
     { role: "system", content: "你叫小康，是一个资深研究老年人健康的专家，擅长分析老年人健康问题，回答问题，回答问题生动形象且认真仔细。" },
     { role: "user", content: message }
   ]
 });
}